import Cookies from 'js-cookie';
import store from '@/store';

/**
 * 权限
 * @param {*} key
 */
export function hasPermission(key) {
  return window.SITE_CONFIG['permissions'].indexOf(key) !== -1 || false;
}

/**
 * 获取字典数据列表
 * @param dictType  字典类型
 */
export function getDictDataList(dictType) {
  const type = window.SITE_CONFIG['dictList'].find((element) => element.dictType === dictType);
  if (type) {
    return type.dataList;
  } else {
    return [];
  }
}

/**
 * 获取字典名称
 * @param dictType  字典类型
 * @param dictValue  字典值
 */
export function getDictLabel(dictType, dictValue) {
  const type = window.SITE_CONFIG['dictList'].find((element) => element.dictType === dictType);
  if (type) {
    const val = type.dataList.find((element) => element.dictValue === dictValue + '');
    if (val) {
      return val.dictLabel;
    } else {
      return dictValue;
    }
  } else {
    return dictValue;
  }
}

/**
 * 清除登录信息
 */
export function clearLoginInfo() {
  store.commit('resetStore');
  Cookies.remove('token');
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = false;
}

/**
 * 获取uuid
 */
export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
  });
}

/**
 * 获取svg图标(id)列表
 */
export function getIconList() {
  var res = [];
  var list = document.querySelectorAll('svg symbol');
  for (var i = 0; i < list.length; i++) {
    res.push(list[i].id);
  }

  return res;
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'pid') {
  var res = [];
  var temp = {};
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i];
  }
  for (var k = 0; k < data.length; k++) {
    if (!temp[data[k][pid]] || data[k][id] === data[k][pid]) {
      res.push(data[k]);
      continue;
    }
    if (!temp[data[k][pid]]['children']) {
      temp[data[k][pid]]['children'] = [];
    }
    temp[data[k][pid]]['children'].push(data[k]);
    data[k]['_level'] = (temp[data[k][pid]]._level || 0) + 1;
  }
  return res;
}

/***
 *
 * 格式化时间
 */
export function formatDate(date, type) {
  //获取年份
  let y = date.getFullYear();
  //获取月份  返回0-11
  let m = date.getMonth() + 1;
  // 获取日
  let d = date.getDate();
  //获取星期几  返回0-6   (0=星期天)
  let w = date.getDay();
  //星期几
  let ww = ' 星期' + '日一二三四五六'.charAt(date.getDay());
  //时
  let h = date.getHours();
  //分
  let minute = date.getMinutes();
  //秒
  let s = date.getSeconds();
  //毫秒
  let sss = date.getMilliseconds();

  if (m < 10) {
    m = '0' + m;
  }
  if (d < 10) {
    d = '0' + d;
  }
  if (h < 10) {
    h = '0' + h;
  }
  if (minute < 10) {
    minute = '0' + minute;
  }
  if (s < 10) {
    s = '0' + s;
  }
  if (sss < 10) {
    sss = '00' + sss;
  } else if (sss < 100) {
    sss = '0' + sss;
  }
  if (type === 'day') {
    return `${y}-${m}-${d}`;
  } else if (type === 'second') {
    return `${y}-${m}-${d} ${h}:${minute}:${s}`;
  }
}

/***
 *
 * 设置系统中基本的表格高度
 *
 */
export function clacTableHeight(date) {
  let content_card = document.getElementById('content_card');
  let top_h = document.getElementById('top_card').offsetHeight;
  content_card.style.height = `calc(100vh - 77px - 40px - 20px - 5px - ${top_h}px)`;
}

/***
 * 将数组对象中的日期进行排序
 * // property是你需要排序传入的key,bol为true时是升序，false为降序
 */
export function sortDateData(property, bol) {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    if (bol) {
      // 升序
      return Date.parse(value1) - Date.parse(value2);
    } else {
      // 降序
      return Date.parse(value2) - Date.parse(value1);
    }
  };
}

/**
 * imagedata类型数据转img数据类型
 * imagedata_to_image
 */
export function imagedata_to_image(imagedata) {
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d');
  canvas.width = imagedata.width;
  canvas.height = imagedata.height;
  ctx.putImageData(imagedata, 0, 0);
  let dataURL = canvas.toDataURL();

  return dataURL;
}

/***
 * 给定日期字符串和指定天数 算出加上的日期
 */
export function addDays(dateString, days) {
  const date = new Date(dateString);
  date.setDate(date.getDate() + Number(days));

  return formatDate(date, 'second');
}
/***
 * 给定日期字符串和指定小时 算出加上的日期
 */
export function addHours(dateString, hours) {
  const date = new Date(dateString);
  let s = Number(hours) * 60 * 60;
  date.setSeconds(date.getSeconds() + s);

  return formatDate(date, 'second');
}

export function downloadFile(url, filename,isEncode) {
  debugger
  // const link = document.createElement('a');
  // link.href = encodeURI(res.data); // 防止中文、括号、空格等出错
  // link.download = ''; // 让浏览器触发下载，而不是打开
  // document.body.appendChild(link);
  // link.click();
  // document.body.removeChild(link);


  const a = document.createElement('a'); // 创建 a 标签
  if(isEncode){
    a.href = encodeURI(url); // 设置文件 URL
  }else {
    a.href = url;
  }
  
  a.download = filename; // 设置下载文件的名称
  a.style.display = 'none'; // 隐藏 a 标签
  document.body.appendChild(a); // 添加到 DOM
  a.click(); // 触发点击事件
  document.body.removeChild(a); // 下载完成后移除 a 标签
}

/**
 * 防抖函数
 * @param {Function} fn 需要防抖的函数
 * @param {number} delay 防抖延迟时间(ms)
 * @returns {Function} 防抖处理后的函数
 */
export function debounce(func, delay = 300, immediate = true) {
  let timer = null;
  return function (...args) {
    const callNow = immediate && !timer; // 是否立即执行

    if (timer) clearTimeout(timer);

    timer = setTimeout(() => {
      timer = null;
      if (!immediate) func.apply(this, args); // 延迟执行
    }, delay);

    if (callNow) func.apply(this, args); // 立即执行
  };
}

// 返回文件的后缀名
export function splitLastDot(str) {
  var lastDotIndex = str.lastIndexOf('.');

  if (lastDotIndex === -1) return [str, ''];

  return str.slice(lastDotIndex + 1);
}

// 比较版本号是不是最新的
export function isOldVersionBool(currentVersion, targetVersion) {
  const current = currentVersion.split('.').map(Number);
  const target = targetVersion.split('.').map(Number);

  for (let i = 0; i < 3; i++) {
    if ((current[i] ?? 0) < (target[i] ?? 0)) return true; // 当前旧
    if ((current[i] ?? 0) > (target[i] ?? 0)) return false; // 当前新
  }
  return false; // 完全一样，不算旧
}
